package com.example.demon.jwt.filters;

import com.example.demon.utils.JwtTokenUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

public class JwtUsernamePasswordFilter extends UsernamePasswordAuthenticationFilter {
    public final AuthenticationManager authenticationManager;

    public JwtUsernamePasswordFilter(AuthenticationManager authenticationManager) {
        this.authenticationManager = authenticationManager;
        this.setFilterProcessesUrl("/api/token");
    }

    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        if (username != null && password != null) {
            UsernamePasswordAuthenticationToken uToken = new UsernamePasswordAuthenticationToken(username, password);
            return authenticationManager.authenticate(uToken);
        } else {
            throw new BadCredentialsException("用户名或密码不能为空");
        }
    }

    protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain, Authentication authResult) throws IOException, ServletException {
        ObjectMapper objectMapper = new ObjectMapper();
        UserDetails userDetails = (UserDetails)authResult.getPrincipal();
        JwtTokenUtil jwtTokenUtil = new JwtTokenUtil();
        String token = jwtTokenUtil.generateToken(userDetails);
        response.setHeader("Authorization", token);
        response.setContentType("application/json;charset=UTF-8");
        Map<String, Object> map = new HashMap(16);
        map.put("code", 200);
        map.put("msg", "登录成功");
        response.getWriter().write(objectMapper.writeValueAsString(map));
    }

    protected void unsuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response, AuthenticationException failed) throws IOException, ServletException {
        ObjectMapper objectMapper = new ObjectMapper();
        response.setContentType("application/json;charset=UTF-8");
        Map<String, Object> map = new HashMap(16);
        map.put("code", 300);
        map.put("msg", failed.getMessage());
        response.getWriter().write(objectMapper.writeValueAsString(map));
    }
}
